package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.DishMapper;
import com.itheima.reggie.domian.Dish;
import com.itheima.reggie.domian.DishFlavor;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    //自定义方法拿到前端传来的DishDto对象,解析分别添加到2个表中


    //添加
    @Transactional
    public void save1(DishDto dishDto) {
        //将表中的数据存入dish表中
        this.save(dishDto);
        //数据保存进dish表中后 dish表自动 生成主键
        //dish表中的主键和口味表的外键相同,将dish表的主键添加进口味表的外键
        //得到dishDto对象中的DishFlavor口味表集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历集合得到每一个口味表,根据菜品表的主键id当成口味表的外键添加进菜品表
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //saveBatch将口味表集合直接存进数据库
        dishFlavorService.saveBatch(flavors);
        //因为同时一个方法操作了多张数据表,需要开启事务
    }


    //修改数据回显
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        //根据客户端传过来的id   得到菜品对象
        Dish dish = this.getById(id);
        //将菜品对象复制到DishDto对象
        BeanUtils.copyProperties(dish, dishDto);
        //根据菜品的id 查询口味表
        LambdaQueryWrapper<DishFlavor> wrap = new LambdaQueryWrapper<>();
        wrap.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(wrap);
        dishDto.setFlavors(list);
        return dishDto;
    }



    //修改保存
    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //将数据保存到菜品表和口味表
        //1.数据保存到菜品表
        this.updateById(dishDto);
        //2.将用户传过来相关的口味全部删除  菜品表主键id=口味表外键id
        LambdaQueryWrapper<DishFlavor> wrap = new LambdaQueryWrapper<>();
        wrap.eq(DishFlavor ::getDishId,dishDto.getId());
        dishFlavorService.remove(wrap);
        //dishFlavorService.removeById(dishDto.getId());
        //3.将客户传过来的口味数据保存到口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
